//
//  ECUIVC_Cash.m
//  Edu_iOS2018
//
//  Created by yanyan on 2018/1/22.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECUIVC_Cash.h"
#import "CYUIView_base.h"
#import "UIView_Helper.h"
#import "ECData_Format.h"
#import "ECUITVCell_Cash.h"
#import "ECManager_Pay.h"
#import "CYUIAlertView.h"
#import "CYDataHelper.h"
#import "ECUIVC_Pay.h"
#import "ECMineCourseOrderViewController.h"
#import "ECUIVC_OrderDetail.h"
@interface ECUIView_CashHeader:CYUIView_base
@property(nonatomic,strong)UIImageView *bgImageView;//背景图片
@property(nonatomic,strong)UILabel *priceTipLabel;//订单价格
@property(nonatomic,strong)UILabel *priceLabel;//价格
@property(nonatomic,strong)UILabel *orderSNLabel;//订单号

@end
@implementation  ECUIView_CashHeader



- (void)addSubviews
{
    [super addSubviews];
    _bgImageView = [UIView_Helper yImageView];
    _bgImageView.image = [UIImage imageNamed:@"orderPay_bgheader"];
    [self addSubview:_bgImageView];
    UIView *subView = [UIView_Helper yView];
    [self.bgImageView addSubview:subView];
    _priceTipLabel = [UIView_Helper yLabel];
    _priceTipLabel.font = [UIFont systemFontOfSize:16];
    _priceTipLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    _priceTipLabel.text = @"订单金额: ";
    [subView addSubview:_priceTipLabel];

    _priceLabel = [UIView_Helper yLabel];
    _priceLabel.font = [UIFont systemFontOfSize:24];
    _priceLabel.textColor = [UIColor colorWithHexString:@"#ef4023"];
    [subView addSubview:_priceLabel];
    
    _orderSNLabel = [UIView_Helper yLabel];
    _orderSNLabel.text = @"订单号：888329898989";
    _orderSNLabel.numberOfLines = 1;
    _orderSNLabel.font = [UIFont systemFontOfSize:13];
    _orderSNLabel.textColor = [UIColor colorWithHexString:@"#808080"];
    [self.bgImageView addSubview:_orderSNLabel];
    WeakSelf(weakSelf);
    CGFloat padding = 60;
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self);
        make.height.equalTo(self.mas_width).multipliedBy(0.4173);
    }];
    [subView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(40));
        make.left.equalTo(weakSelf.bgImageView.mas_left).offset(padding);
        make.right.equalTo(weakSelf).offset(-padding);
        make.centerX.equalTo(self.bgImageView);
        make.bottom.equalTo(self.orderSNLabel.mas_top);
    }];
    [self.priceTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(subView);
        make.left.height.equalTo(subView);
        make.width.equalTo(@(80));
    }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(subView);
        make.height.equalTo(subView);
        make.left.equalTo(self.priceTipLabel.mas_right).offset(5);
        make.right.equalTo(subView);
    }];
    [self.orderSNLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(subView.mas_bottom);
        make.height.equalTo(@(30));
        make.left.equalTo(subView.mas_left).offset(5);
        make.right.equalTo(subView);
        make.bottom.equalTo(self.bgImageView).offset(-20);
    }];
}
- (void)setObject:(id)object
{
    [super setObject:object];
    ECCourseOrderModel *mo = object;
    self.priceLabel.attributedText = [ECFormatHelper attributedStringForPromotionPrice:mo.totalPrice decimal:2];
    self.orderSNLabel.text = [NSString stringWithFormat:@"订单号：%@",mo.orderSN];

}
@end
@interface ECUIVC_Cash ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)UILabel *tipLabel;//订单支付提示语
@property(nonatomic,strong)ECUIView_CashHeader *headerView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation ECUIVC_Cash
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti_alipaySuccess:) name:kNotifactionAlipayPaySuccess object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti_alipayFailure:) name:kNotifactionAlipayPayFail object:nil];
    }
    return self;
}
- (void)noti_alipayFailure:(NSNotification *)noti{
    NSString *message = @"支付失败";
    if (noti.object) {
        message = [noti.object valueForKey:@"memo"];
    }
//    WeakSelf(weakSelf);
//    CYUIAlertView *uiview_alert = [[CYUIAlertView alloc]initWithAlertViewTitle:@"支付结果" message:message cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
//    [uiview_alert showAlertViewInViewController:self.navigationController];
//    uiview_alert.block_cancel = ^{
//        [weakSelf payFailure];
//    };
    WeakSelf(weakSelf);
    DLog(@"在什么线程 ：%d",[[NSThread currentThread] isMainThread]);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showTipMessageInWindow:message];
    });

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kPayResultShowDuration*NSEC_PER_SEC), dispatch_get_main_queue(), ^{

            [weakSelf payFailure];
            
        });
    });
}
-(void)showHudString:(NSString *)message
{
    DLog(@"在主线程 ：%d",[[NSThread currentThread] isMainThread]);
//    [MBProgressHUD showTipMessageInWindow:message];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

}
#pragma mark - 支付宝或者微信支付失败 -
- (void)payFailure{
    // 支付失败：1.课程详情->订单待支付 2.订单列表-> 订单列表
    UITabBarController *uivc_tab = (UITabBarController *)[[[UIApplication sharedApplication] keyWindow] rootViewController];
//   1.课程详情->订单待支付
    if (uivc_tab.selectedIndex != 2) {
        NSArray *uivcArrs = self.navigationController.viewControllers;
        UIViewController *uivc = uivcArrs[uivcArrs.count - 2];
        if ([uivc isMemberOfClass:[ECUIVC_Pay class]] || [uivc isMemberOfClass:[ECUIVC_OrderDetail class]]) {
            [self.navigationController popToViewController:uivcArrs[uivcArrs.count - 3] animated:NO];
        } else {
            [self.navigationController popViewControllerAnimated:NO];
        }
        uivc_tab.selectedIndex = 2;
        [self showOrderListForUnPay: uivc_tab.selectedViewController];
    } else {
        NSArray *uivcArrs = self.navigationController.viewControllers;
        UIViewController *uivc = uivcArrs[uivcArrs.count - 2];
        //  ->
        if ([uivc isMemberOfClass:[ECUIVC_Pay class]] || [uivc isMemberOfClass:[ECUIVC_OrderDetail class]]) {
            [self.navigationController popToViewController:uivcArrs[uivcArrs.count - 3] animated:NO];
        } else {
            [self.navigationController popViewControllerAnimated:NO];
        }
    }
    
    
    
}
- (void)noti_alipaySuccess:(NSNotification *)noti{
    
    WeakSelf(weakSelf);
    [MBProgressHUD showTipMessageInView:@"支付成功" timer:kPayResultShowDuration];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kPayResultShowDuration*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [weakSelf paySuccessBack];
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotifactionPaySuccess object:nil];
            
        });
    });
    
}
- (void)paySuccessBack{
    //  支付成功：1、 课程详情>结算中心>提交订单--->课程详情；2、订单列表:待支付/全部->已支付；
    NSArray *uivcArrs = self.navigationController.viewControllers;
    UIViewController *uivc = uivcArrs[uivcArrs.count - 2];
    if ([uivc isMemberOfClass:[ECUIVC_Pay class]] || [uivc isMemberOfClass:[ECUIVC_OrderDetail class]]) {
        [self.navigationController popToViewController:uivcArrs[uivcArrs.count - 3] animated:NO];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"订单支付";
    [self.bottomView addSubview:self.headerView];
    self.tableView.tableHeaderView = self.bottomView;
    [self.view addSubview:self.tableView];
    UILabel *styleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, self.bottomView.height - 38, 160, 38)];
    styleLabel.text = @"选择支付方式";
    styleLabel.contentMode = UIViewContentModeCenter;
    styleLabel.textColor = [UIColor colorWithHex:0x808080];
    styleLabel.font = [UIFont systemFontOfSize:14];
    [self.bottomView addSubview:styleLabel];
    if (self.object) {
        [self writeView];
    }
}
- (void)addBarButtons
{
    [super addBarButtons];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [button setImage:[UIImage imageNamed:@"Mine_back"] forState:0];
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button addTarget:self action:@selector(action_back:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
- (void)action_back:(id)sender{
    NSArray *uivcArrs = self.navigationController.viewControllers;
    UIViewController *uivc = uivcArrs[uivcArrs.count - 2];
    if ([uivc isMemberOfClass:[ECUIVC_Pay class]]) {
        [self.navigationController popToViewController:uivcArrs[uivcArrs.count - 3] animated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)writeView
{
    [super writeView];
    self.dataSource = [ECData_Format arrayForOrderCashStyle:nil];
    self.headerView.object = self.object;
    [self.tableView reloadData];
}
- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 230)];
        _bottomView.backgroundColor = [UIColor colorWithHex:0xf5f5f5];
        _tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kProportion_Height(90))];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.textColor = [UIColor colorWithHex:0xef4023];
        _tipLabel.backgroundColor = [UIColor colorWithHex:0xfdece6];
        _tipLabel.text = @"请在48小时内完成支付，逾期订单将被取消";
        _tipLabel.font = [UIFont systemFontOfSize:12];
        [_bottomView addSubview:_tipLabel];
    }
    return _bottomView;
}

-(ECUIView_CashHeader *)headerView
{
    if (!_headerView) {
        
        _headerView = [[ECUIView_CashHeader alloc]initWithFrame:CGRectMake(0, kProportion_Height(90), kScreenWidth, kScreenWidth * 0.4174)];
        
    }
    return _headerView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.view.height-50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = kProportion_Height(180);
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        [_tableView registerClass:[ECUITVCell_Cash class] forCellReuseIdentifier:@"cell"];
    }
    return _tableView;
}
- (void)setObject:(id)object
{
    [super setObject:object];
   
}

#pragma mark - delegate -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ECUITVCell_Cash *cell = (ECUITVCell_Cash *)[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"orderPay_arrow"]];
    id obj = [self.dataSource objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor colorWithHex:0x333333];
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.textLabel.text = [obj valueForKey:@"name"];
    cell.detailTextLabel.text = [obj valueForKey:@"brief"];
    cell.detailTextLabel.textColor = [UIColor colorWithHex:0xb3b3b3];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
    cell.imageView.image = [UIImage imageNamed:[obj valueForKey:@"image"]];
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        cell.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        cell.layoutMargins = UIEdgeInsetsZero;
    }
    
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        cell.preservesSuperviewLayoutMargins = false;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 支付方式
    NSString *payStyle = @"alipay";
    if (indexPath.row == 1) {
        // 微信支付
        payStyle = @"wxpay";
    }
    [self payStyle:@{@"payment":payStyle}];
}
-(void)payStyle:(NSDictionary*)dict
{
    WeakSelf(weakSelf);
    ECCourseOrderModel *mo = self.object;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HWHttpTool requestWithMethod:@"POST" url:URL_CommitOrderWithOrderId(mo.orderId) params:dict headers:@{URL_SERVER_HEADER_USERTOKEN_KEY : [[UserInfoManager shareUser] token]} success:^(id json) {
        DLog(@"支付----   %@",json);
        [MBProgressHUD hideHUD];
        id data = [json valueForKey:@"data"];
        if ([[dict valueForKey:@"payment"] isEqualToString:@"wxpay"]) {
            if (![CYDataHelper isNull:data] && [data valueForKey:@"appid"]) {
                [[ECManager_Pay sharedInstance] payOrder:data finished:^(id json) {
                    DLog(@"微信支付完成:%@",json);
                    SendAuthResp *resp = json;
                    [weakSelf payResultForWeiXin:resp];
                }];
            } else {
                [MBProgressHUD showErrorMessage:@"请求失败"];
            }
        } else {

            [[ECManager_Pay sharedInstance] payAliOrder:[data valueForKey:@"orderString"]  finished:^(id json) {
                DLog(@"支付宝支付结果 ：%@",json);
            }];
        }
        
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"请求失败"];

    }];
}
-(void)payResultForWeiXin:(SendAuthResp *)resp
{
    //支付返回结果，实际支付结果需要去微信服务器端查询
    NSString *strMsg = @"支付结果";
    
    switch (resp.errCode) {
        case WXSuccess:
            strMsg = @"支付成功！";
            break;
        case WXErrCodeUserCancel:
            strMsg = @"支付取消";
            break;
        default:
            strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
            break;
    }
    WeakSelf(weakSelf);
        [MBProgressHUD showTipMessageInView:strMsg timer:kPayResultShowDuration];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kPayResultShowDuration*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                if (resp.errCode == WXSuccess) {

                [weakSelf paySuccessBack];
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotifactionPaySuccess object:nil];
                } else {
                    [weakSelf payFailure];
                }
            });
        });
        
    
}
-(void)showOrderListForUnPay:(UINavigationController *)sender{
    dispatch_async(dispatch_get_main_queue(), ^{
        ECMineCourseOrderViewController *vc = [[ECMineCourseOrderViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.selectedIndex = 1;
        [sender pushViewController:vc animated:YES];
    });
  

}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
